
//
// 120322 - AH - (Midtun) Created.
// 120407 - AH - (Midtun) Form text fix.
// 120521 - AH - (Garage & Huset) selecting of engine.
// 120626 - AH - (Huset *) Took in use ACCOUNT_ID, CE_NAME, ENGINE and
//               RAT_BASE_ID.
// 120824 - AH - (Lib. Nesttun) Removed old debug printout.
//

package org.soekrat.server.servlets.ce;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.japril.servlet.HttpRequestDef;
import org.soekrat.server.io.db.Account;
import org.soekrat.server.io.db.ConversationElement;
import org.soekrat.server.io.db.SoekratDAO;
import org.soekrat.server.io.db.SoekratDAOFactory;
import org.soekrat.server.serialization.ConversationElementSerializable;
import org.soekrat.server.servlets.AbstractSoekratHttpServlet;

/**
 * <p>
 *   Implements requests to create a
 *   {@link ConversationElement} for a given
 *   {@link Account}.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
@SuppressWarnings("serial")
public final class CreateConversationElementHttpServlet
  extends AbstractSoekratHttpServlet
{
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public CreateConversationElementHttpServlet(){}

  @Override
  protected void handleRequest(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    HttpRequestDef def=getHttpRequestDef();
    
    if (!hasParameters(req))
    {
      PrintWriter pw=printSimpleHtmlStart(res);
      pw.println(def.compileApiHtml());
      printSimpleHtmlEnd(pw);
    }
    else
    { 
      if (!validate(res, def, req)) return;
      
      long akey=def.fetch(ACCOUNT_ID.name(), req).getLongValue();
      
      SoekratDAO dao=new SoekratDAOFactory().create();
      Account owner=dao.getAccount(akey);
      
      if (owner==null)
      {
        respond(res, "Could not find account for key: "+akey);
      }
        
      Map<String, String> pm=getParameterMap(req, ACCOUNT_ID.name(), 
        CE_ID.name());
        
      ConversationElement ced=dao.createConversationElement(owner, pm);
        
      respond(res, new ConversationElementSerializable(ced));
    }
  }
  
  @Override
  public HttpRequestDef getHttpRequestDef()
  {
    HttpRequestDef retVal=new HttpRequestDef("/soekrat_server/create_ce")
      .desc("Create Conversation Element").parameter(ACCOUNT_ID)
      .parameter(CE_NAME).parameter(ENGINE).parameter(RAT_BASE_ID);
    return retVal;
  }

}
